<script setup lang="ts">
import { Download, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { ComponentPublicInstance, computed, reactive, ref, watch } from "vue"
import {
  IGetApplyListFileResponseData,
  IGetApplyListRequestData,
  IGetApplyListResponseData,
  IGetMultiConditionQueryResponseData
} from "@/api/files/types/files"
import { usePagination } from "@/hooks/usePagination"
import { fileDownloadApi, getFileApplyListApi } from "@/api/files"
import { IGetDepartmentData } from "@/api/department/types/department"
import { getDepartmentIdAndNameList } from "@/api/department"
import { GetProjectIdAndNameList } from "@/api/project"
import { IGetProjectIdAndNameResponseData } from "@/api/project/types/project"
import { useUserStore } from "@/store/modules/user"
import { openDownload, previewOnNewTab, showPromptMessage } from "@/utils"
import { genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus"
import { IUserInfoData } from "@/api/login/types/login"
import { getAdminByNameDataApi } from "@/api/admin"
import { IGetAdminByNameData } from "@/api/admin/types/admin"
import { getToken } from "@/utils/cache/cookies"
const loading = ref(false)
const userStore = useUserStore()
const userInfo = userStore.userInfo as IUserInfoData
const searchData = reactive<IGetApplyListRequestData>({
  theYear: "",
  projectId: undefined,
  isPass: undefined,
  isNecessary: undefined,
  uploaderId: undefined,
  departmentId: userInfo.departmentId
})
// 查询
const necessaryOptions = [
  {
    label: "补充资料",
    value: 0
  },
  {
    label: "必要资料",
    value: 1
  }
]

const auditStatus = [
  {
    label: "未通过/驳回",
    value: 0
  },

  {
    label: "通过",
    value: 1
  }
]

const FilesData = ref<IGetApplyListResponseData[]>([])
const DepartmentData = ref<IGetDepartmentData[]>([])
const ProjectData = ref<IGetProjectIdAndNameResponseData[]>([])
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const refreshing = ref(false)
const getFilesDataList = () => {
  if (refreshing.value) return
  refreshing.value = true
  loading.value = true
  getFileApplyListApi(
    { page: paginationData.currentPage, size: paginationData.pageSize, departmentId: userInfo.departmentId },
    searchData
  )
    .then((res) => {
      res.data.list.map((el) => {
        el.files.map((file, index) => {
          const current = file
          const next = el.files[index + 1]
          if (index < el.files.length - 1) {
            if (next.version > current.version) {
              current.versionType = "old"
            } else {
              current.versionType = "new"
            }
          } else {
            current.versionType = "new"
          }
        })
      })
      FilesData.value = res.data.list
      paginationData.total = res.data.total
    })
    .catch(() => {
      FilesData.value = []
    })
    .finally(() => {
      refreshing.value = false
      loading.value = false
    })
}
defineExpose({ getFilesDataList })

const getDepartmentDataList = () => {
  getDepartmentIdAndNameList({ name: "", departmentId: userInfo.departmentId })
    .then((res) => {
      DepartmentData.value = res.data.list
    })
    .catch(() => {
      DepartmentData.value = []
    })
}
getDepartmentDataList()

const getProjectDataList = () => {
  GetProjectIdAndNameList({ name: "", departmentId: searchData.departmentId })
    .then((res) => {
      ProjectData.value = res.data.list
    })
    .catch(() => {
      ProjectData.value = []
    })
}
getProjectDataList()
const resetSearch = () => {
  searchData.projectId = undefined
  searchData.isNecessary = undefined
  searchData.departmentId = undefined
  searchData.theYear = ""
  searchData.isPass = undefined
  if (paginationData.currentPage === 1) {
    getFilesDataList()
  }
  paginationData.currentPage = 1
}

const handleRefresh = () => {
  getFilesDataList()
}

// 下载
const handleDownload = (data: IGetMultiConditionQueryResponseData) => {
  fileDownloadApi(userStore.userInfo!.id, [data.id]).then((res) => {
    openDownload(res.blob, res.fileName)
  })
}
const downloadItems = ref<IGetMultiConditionQueryResponseData[]>([])
const downloadIds = computed(() => {
  return downloadItems.value.map((item) => item.id)
})
const handleBatchDownload = () => {
  loading.value = true
  fileDownloadApi(userStore.userInfo!.id, downloadIds.value).then((res) => {
    openDownload(res.blob, res.fileName)
    loading.value = false
  })
}
const handleSelectionChange = (val: IGetMultiConditionQueryResponseData[]) => {
  downloadItems.value = val
}

type types = Element | ComponentPublicInstance | null
const activeNames = ref<number>()
const tableRefs = ref<{ [key: number]: types }>({})
const auditStatusObj = {
  0: "未审核",
  1: "驳回",
  2: "通过"
}

const previewUrl = ref("")
const previewVisible = ref(false)

const handlePreview = (row: IGetApplyListFileResponseData) => {
  previewOnNewTab(row.url)
}

const reUploadVisible = ref(false)
const upload = ref<UploadInstance | null>(null)
const currentReUploadId = ref<undefined | number>(undefined)
const currentUploadFile = ref("")
const handleReupload = (row: IGetApplyListFileResponseData) => {
  currentReUploadId.value = row.id
  reUploadVisible.value = true
}
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value?.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handleSuccess: UploadProps["onSuccess"] = (response) => {
  reUploadVisible.value = false
  loading.value = false
  if (response.code === 200) {
    showPromptMessage("success", "重传成功")
    getFilesDataList()
  } else {
    showPromptMessage("error", response.message)
  }
}
const handleBeforeUpload: UploadProps["beforeUpload"] = () => {
  loading.value = true
}
const handleChange: UploadProps["onChange"] = (uploadFile) => {
  currentUploadFile.value = uploadFile.name
}
const AdminData = ref<IGetAdminByNameData[]>([])

const getAdminData = () => {
  getAdminByNameDataApi({ name: "", departmentId: searchData.departmentId }).then((res) => {
    AdminData.value = res.data.users
  })
}
getAdminData()
const handleConfirmReUpload = () => {
  upload.value?.submit()
}

watch([() => paginationData], getFilesDataList, { deep: true })

watch(
  [
    () => searchData.theYear,
    () => searchData.isNecessary,
    () => searchData.isPass,
    () => searchData.projectId,
    () => searchData.uploaderId
  ],
  getFilesDataList,
  {
    deep: true,
    immediate: true
  }
)

watch(
  [() => searchData.departmentId],
  () => {
    searchData.projectId = undefined
    getProjectDataList()
    getFilesDataList()
    getAdminData()
  },
  {
    deep: true
  }
)
</script>

<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中">
    <el-card shadow="never" class="my-5">
      <el-form inline ref="inlineFormRef" :model="searchData" label-width="70">
        <el-form-item prop="uploaderId" label="上传者">
          <el-select filterable v-model="searchData.uploaderId" placeholder="选择上传者">
            <el-option v-for="item in AdminData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="departmentId" label="办学单位" v-if="userInfo.authority === '2'">
          <el-select filterable v-model="searchData.departmentId" placeholder="选择办学单位">
            <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="projectId" label="培训项目">
          <el-select filterable v-model="searchData.projectId" placeholder="选择培训项目">
            <el-option v-for="item in ProjectData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="theYear" label="立项年度">
          <el-date-picker v-model="searchData.theYear" type="year" value-format="YYYY" placeholder="选择立项年度" />
        </el-form-item>
        <el-form-item prop="isPass" label="审核状态">
          <el-select filterable v-model="searchData.isPass" placeholder="选择审核状态">
            <el-option v-for="item in auditStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="资料类型">
          <el-select filterable v-model="searchData.isNecessary" placeholder="选择资料类型">
            <el-option v-for="item in necessaryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button :icon="Refresh" @click="resetSearch" type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="flex justify-end">
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="mt-5">
        <el-collapse accordion v-model="activeNames">
          <el-collapse-item :name="item.id" v-for="item in FilesData" :key="item.id">
            <template #title>
              <div class="flex items-center">
                <span>{{ item.departmentName }}</span>
                <div class="text-blue-400 text-sm ml-5 font-semibold">{{ item.theYear }}</div>
                <!-- 悬浮气泡显示完整项目名 -->
                <div :title="item.projectName" class="text-gray-500 text-xs ml-5 text-center w-80 one">
                  <!-- <el-tooltip v-if="item.projectName" placement="top" effect="dark" :offset="5" :show-arrow="false">
                    <template #content>
                      <span>{{ item.projectName }}</span>
                    </template>
                    <span>{{
                      item.projectName.length > 20 ? item.projectName.slice(0, 20) + "..." : item.projectName
                    }}</span>
                  </el-tooltip> -->

                  <div class="w-full one" v-if="item.projectName">
                    {{ item.projectName }}
                  </div>
                  <span v-else>未知项目</span>
                </div>

                <div class="w-20 flex justify-center">
                  <el-tag class="ml-5" :type="item.isNecessary ? 'danger' : 'info'">{{
                    item.isNecessary ? "必要资料" : "补充资料"
                  }}</el-tag>
                </div>
                <span class="text-gray-300 text-xs ml-5" v-if="item.note">备注信息:{{ item.note }}</span>
              </div>
            </template>
            <el-descriptions>
              <el-descriptions-item>
                <div>
                  <el-button
                    type="primary"
                    :disabled="downloadIds.length === 0"
                    :icon="Download"
                    @click="handleBatchDownload"
                  >
                    批量下载
                  </el-button>
                </div>
                <el-table
                  class="mt-2"
                  :ref="
                    (el) => {
                      tableRefs[item.id] = el
                    }
                  "
                  @selection-change="handleSelectionChange"
                  border
                  :data="item.files"
                  style="width: 100%"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column prop="name" label="文件名称" show-overflow-tooltip />
                  <el-table-column prop="version" label="版本号" />
                  <el-table-column prop="versionType" label="版本比较">
                    <template #default="scope">
                      <el-tag type="success" v-if="scope.row.versionType === 'new'"> 新版本 </el-tag>

                      <el-tag type="info" v-if="scope.row.versionType === 'old'"> 旧版本 </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="cause" label="驳回原因" />
                  <el-table-column prop="auditStatus" label="审核状态">
                    <template #default="scope">
                      <el-tag
                        :type="scope.row.auditStatus === 0 ? '' : scope.row.auditStatus === 1 ? 'danger' : 'success'"
                      >
                        {{ auditStatusObj[(scope.row as IGetApplyListFileResponseData).auditStatus] }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="note" label="备注信息" />
                  <el-table-column fixed="right" label="操作" width="220" align="center">
                    <template #default="scope">
                      <el-button
                        v-if="scope.row.auditStatus !== 2"
                        type="primary"
                        text
                        bg
                        size="small"
                        @click="handleReupload(scope.row)"
                        >重传</el-button
                      >
                      <el-button type="primary" text bg size="small" @click="handlePreview(scope.row)">预览</el-button>
                      <el-button type="primary" text bg size="small" @click="handleDownload(scope.row)">下载</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!--      <div class="mt-5">-->
      <!--        <el-table @selection-change="handleSelectionChange" :data="FilesData">-->
      <!--          <el-table-column type="selection" width="55" />-->
      <!--          <el-table-column prop="name" :show-overflow-tooltip="true" label="文件名" align="center" />-->
      <!--          <el-table-column prop="theYear" label="立项年度" align="center" />-->
      <!--          <el-table-column prop="departmentName" label="机构名称" align="center" />-->
      <!--          <el-table-column prop="projectName" label="项目名称" align="center" />-->
      <!--          <el-table-column prop="isNecessary" label="是否必须" align="center">-->
      <!--            <template #default="scope">-->
      <!--              {{ scope.row.isNecessary === 0 ? "否" : "是" }}-->
      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--          <el-table-column prop="auditStatus" label="审核状态" align="center">-->
      <!--            <template #default="scope">-->
      <!--              <el-tag :type="scope.row.auditStatus === 0 ? '' : scope.row.auditStatus === 1 ? 'danger' : 'success'">-->
      <!--                {{ scope.row.auditStatus === 0 ? "未审核" : scope.row.auditStatus === 1 ? "驳回" : "通过" }}-->
      <!--              </el-tag>-->
      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--          <el-table-column prop="cause" label="驳回原因" align="center" />-->
      <!--          <el-table-column prop="note" label="备注" align="center" />-->
      <!--          <el-table-column fixed="right" label="操作" width="220" align="center">-->
      <!--            <template #default="scope">-->
      <!--              <el-button type="primary" text bg size="small" @click="handleDownload(scope.row)">下载</el-button>-->
      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--        </el-table>-->
      <!--      </div>-->
      <div class="mt-5">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!--    预览窗口-->
    <el-dialog v-model="previewVisible">
      <div>
        <iframe v-if="previewUrl" :src="previewUrl" />
      </div>
    </el-dialog>

    <!--    重传窗口-->
    <el-dialog title="文件重传" v-model="reUploadVisible">
      <el-upload
        ref="upload"
        class="upload-demo"
        :action="'/api/v2/file/reload?id=' + currentReUploadId"
        :limit="1"
        method="put"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :before-upload="handleBeforeUpload"
        :auto-upload="false"
        :headers="{ token: getToken() }"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reUploadVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmReUpload"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
